package com.jcsz.sso.client.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;

/**
 * @className: ClientController
 * @author: 一把Po吉他
 * @date: 2022/11/9 20:47
 * @version: 1.0
 **/
@Controller
public class ClientController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("msg", "无需登录即可访问.....");
        return "hello";
    }

    @GetMapping("/list")
    public String list(@RequestParam(value = "token", required = false) String token, HttpSession session, Model model) {
        if (!StringUtils.isEmpty(token)) {
            //String username = redisTemplate.opsForValue().get(token);
            RestTemplate restTemplate = new RestTemplate();
            String forObject = restTemplate.getForObject("http://server.sso.com:30080/userInfo?token=" + token, String.class);
            session.setAttribute("loginUser", forObject);
            model.addAttribute("loginUser", forObject);
            return "list";
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:http://server.sso.com:30080/login.html?redirect_url=http://client.sso.com:30086/list";
        }
        model.addAttribute("msg", "已登录,可访问.....");
        return "list";
    }
}
